package com.generalbackend.common.service.impl;

import com.generalbackend.common.exception.EToolsRuntimeException;
import com.generalbackend.common.service.IFileService;
import com.generalbackend.common.util.CheckFileUtil;
import com.generalbackend.common.util.ResponseUtil;
import com.generalbackend.common.util.SnowFlakeIdGeneratorUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;

/**
 * @author tim.xie
 * @date 2022/1/21 15:27
 */
@Service
public class FileServiceImpl implements IFileService {

    @Value("${general.save-folder}")
    private String saveFolderPath;
    private static String COMMON_FOLDER_PATH = "common";

    @Override
    public String uploadFile(MultipartFile file) throws IOException {
        return saveFile(file, COMMON_FOLDER_PATH);
    }

    @Override
    public String uploadFile(MultipartFile file, String childDir) throws IOException {
        return saveFile(file, childDir);
    }

    /**
     * 保存文件
     * @param file
     * @param childDir
     *      子目录
     * @return
     * @throws IOException
     */
    public String saveFile(MultipartFile file, String childDir) throws IOException {
        CheckFileUtil.checkUploadFile(file.getOriginalFilename());
        String originalFileName = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'));
        // 使用雪花id作为目录的一部分
        String randomFolder = String.valueOf(SnowFlakeIdGeneratorUtil.nextId());
        String dirPath = saveFolderPath + childDir + File.separator + randomFolder + File.separator;
        File dirFile = new File(dirPath);
        if (dirFile.exists() || dirFile.mkdirs()) {
            String filePath = dirPath + originalFileName + suffix;
            file.transferTo(new File(filePath));
            return childDir + "/" + randomFolder + "/" + originalFileName + suffix;
        } else {
            throw new EToolsRuntimeException(String.format("创建目录%s失败",dirPath));
        }
    }

    @Override
    public void downloadFile(HttpServletResponse response, String childDir, String randomFolder, String fileName) {
        String path = saveFolderPath + String.join(File.separator, Arrays.asList(childDir, randomFolder, fileName));
        ResponseUtil.responseFile(response, path);
    }

}
